package puziran.sofa.memcache.session;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import puziran.sofa.util.ReadPropertiesFile;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class MemService {
	private static MemCachedClient cachedClient = new MemCachedClient();
	private static int expiryTime = 480;

	static {
		SockIOPool pool = SockIOPool.getInstance();

		String[] servers = ReadPropertiesFile.getString("config/application",
				"smip").split(",");
		for (int i = 0; i < servers.length; i++) {
			System.out.println("servers[" + i + "]=" + servers[i]);
		}
		Integer[] weights = { Integer.valueOf(3) };

		pool.setServers(servers);
		pool.setWeights(weights);

		pool.setInitConn(10);
		pool.setMinConn(10);
		pool.setMaxConn(1000);
		pool.setMaxIdle(3600000L);

		pool.setMaintSleep(60L);

		pool.setNagle(false);
		pool.setSocketTO(60);
		pool.setSocketConnectTO(0);

		pool.initialize();
	}

	public static boolean sessionExists(String id) {
		return cachedClient.keyExists(id);
	}

	public static Map getSession(String id, boolean create) {
		Map session = (Map) cachedClient.get(id);
		if ((session == null) && (create)) {
			session = new HashMap(5);
			cachedClient.add(id, session, getExpiryDate());
		}

		return session;
	}

	public static void setSession(String id, Map session) {
		if (cachedClient.keyExists(id)) {
			cachedClient.replace(id, session, getExpiryDate());
		} else
			cachedClient.add(id, session, getExpiryDate());
	}

	public static void setSession(String id, Map session, Date expiryDate) {
		if (cachedClient.keyExists(id))
			cachedClient.replace(id, session, expiryDate);
		else
			cachedClient.add(id, session, expiryDate);
	}

	public static void removeSession(String id) {
		cachedClient.delete(id);
	}

	public static void updateExpiryDate(String id) {
		Map session = (Map) cachedClient.get(id);
		if (session != null)
			cachedClient.replace(id, session, getExpiryDate());
	}

	private static Date getExpiryDate() {
		Calendar calendar = Calendar.getInstance();

		long time = calendar.getTimeInMillis();
		time += expiryTime * 60 * 1000;
		calendar.setTimeInMillis(time);

		return calendar.getTime();
	}
}